<template>
  <div class="task-pool-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>全局在制任务池</span>
          <el-button :icon="Refresh" @click="fetchTasks" :loading="loading">刷新</el-button>
        </div>
      </template>

      <el-table :data="tasks" v-loading="loading" border style="width: 100%">
        <el-table-column prop="pieceId" label="工件ID" width="180" />
        <el-table-column prop="productName" label="产品名称" />

        <el-table-column prop="workstationName" label="所在工位">
          <template #default="scope">
            <el-link type="primary" @click="goToWorkstation(scope.row.workstationId)">
              {{ scope.row.workstationId }}号工位 ({{ scope.row.workstationName }})
            </el-link>
          </template>
        </el-table-column>

        <el-table-column prop="processName" label="当前工序">
          <template #default="scope">
            {{ scope.row.processName }} ({{ scope.row.processId }})
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 2 ? 'success' : 'info'">
              {{ scope.row.statusText }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { getActiveTasks } from '@/api/modules/dispatch';
import { Refresh } from '@element-plus/icons-vue'

const loading = ref(true);
const tasks = ref([]);
const router = useRouter();

const fetchTasks = async () => {
  loading.value = true;
  try {
    tasks.value = await getActiveTasks();
  } catch(error) {
    console.error("获取全局任务失败", error);
  } finally {
    loading.value = false;
  }
}

const goToWorkstation = (workstationId) => {
  router.push({
    path: '/mes/workstation-board',
    query: { wsid: workstationId }
  });
}

onMounted(fetchTasks);
</script>

<style scoped>
.task-pool-container { padding: 20px; }
.card-header { display: flex; justify-content: space-between; align-items: center; font-weight: bold; }
</style>
